<!-- V-webapp/src/views/PaymentView.vue -->
<template>
  <div class="payment-container">
    <div class="page-header">
      <el-button @click="$router.back()" class="back-btn" type="primary" link>
        <el-icon><ArrowLeft /></el-icon>
      </el-button>
      <h2>订单支付</h2>
    </div>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>

    <div v-else class="payment-content">
      <!-- 订单信息 -->
      <div class="section-card">
        <h3 class="section-title">订单信息</h3>
        <div class="order-info">
          <p><strong>订单号:</strong> {{ orderInfo.order_number }}</p>
          <p><strong>订单金额:</strong> <span class="amount">¥{{ orderInfo.total_amount }}</span></p>
          <p><strong>创建时间:</strong> {{ formatDate(orderInfo.created_at) }}</p>
        </div>
      </div>

      <!-- 支付方式 -->
      <div class="section-card">
        <h3 class="section-title">选择支付方式</h3>
        <div class="payment-methods">
          <div 
            v-for="method in paymentMethods" 
            :key="method.value"
            class="payment-method"
            :class="{ active: selectedMethod === method.value }"
            @click="selectedMethod = method.value"
          >
            <el-icon class="method-icon"><component :is="method.icon" /></el-icon>
            <span class="method-name">{{ method.name }}</span>
            <el-icon v-if="selectedMethod === method.value" class="check-icon"><Check /></el-icon>
          </div>
        </div>
      </div>

      <!-- 支付按钮 -->
      <div class="payment-actions">
        <el-button 
          type="primary" 
          class="pay-btn"
          :loading="paying"
          @click="handlePayment"
        >
          {{ paying ? '支付中...' : `确认支付 ¥${orderInfo.total_amount}` }}
        </el-button>
        <el-button 
          type="default" 
          @click="$router.back()"
        >
          取消支付
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Check, Money, CreditCard, Iphone } from '@element-plus/icons-vue'
import { getOrderById, processPayment } from '@/api/orders'

const router = useRouter()
const route = useRoute()
const loading = ref(true)
const paying = ref(false)

const orderInfo = ref({
  order_id: 0,
  order_number: '',
  total_amount: 0,
  created_at: ''
})

const paymentMethods = [
  { value: 'alipay', name: '支付宝', icon: 'CreditCard' },
  { value: 'wechat', name: '微信支付', icon: 'Iphone' },
  { value: 'balance', name: '余额支付', icon: 'Money' }
]

const selectedMethod = ref('alipay')

// 加载订单信息
const loadOrderInfo = async () => {
  try {
    loading.value = true
    const orderId = route.query.order_id as string
    if (!orderId) {
      ElMessage.error('订单信息不存在')
      router.push('/cart')
      return
    }

    const response = await getOrderById(parseInt(orderId))
    if (response.success) {
      orderInfo.value = response.data
    } else {
      throw new Error(response.message || '获取订单信息失败')
    }
  } catch (error: any) {
    console.error('❌ 加载订单信息失败:', error)
    ElMessage.error(error.message || '加载订单信息失败')
    router.push('/cart')
  } finally {
    loading.value = false
  }
}

// 处理支付
const handlePayment = async () => {
  try {
    paying.value = true
    console.log('💰 开始支付:', orderInfo.value.order_id)

    const response = await processPayment(orderInfo.value.order_id)
    console.log('✅ 支付响应:', response)

    if (response.success) {
      ElMessage.success('支付成功！')
      
      // 跳转到支付成功页面
      router.push({
        path: '/payment/success',
        query: { 
          order_id: orderInfo.value.order_id,
          order_number: orderInfo.value.order_number
        }
      })
    } else {
      throw new Error(response.message || '支付失败')
    }
  } catch (error: any) {
    console.error('❌ 支付失败:', error)
    ElMessage.error(error.response?.data?.message || error.message || '支付失败')
  } finally {
    paying.value = false
  }
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

onMounted(() => {
  loadOrderInfo()
})
</script>

<style scoped>
.payment-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 16px;
  padding-bottom: 100px; /* 为底部支付按钮留出空间 */
}

.page-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.loading-container {
  padding: 40px 0;
}

.section-card {
  background: white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.section-title {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.order-info p {
  margin: 8px 0;
  font-size: 14px;
  color: #666;
}

.amount {
  font-size: 18px;
  font-weight: 700;
  color: #ff4757;
}

.payment-methods {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.payment-method {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border: 2px solid #f0f0f0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.payment-method:hover {
  border-color: #667eea;
}

.payment-method.active {
  border-color: #667eea;
  background: #f0f4ff;
}

.method-icon {
  font-size: 24px;
  color: #667eea;
}

.method-name {
  flex: 1;
  font-size: 16px;
  font-weight: 500;
}

.check-icon {
  color: #52c41a;
}

.payment-actions {
  position: fixed;
  bottom: 60px; /* 调整到合适的位置，在下导航栏正上方 */
  left: 50%;
  transform: translateX(-50%);
  background: white;
  padding: 12px 20px;
  display: flex;
  gap: 12px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 480px;
  box-sizing: border-box;
  z-index: 1000;
  border-radius: 12px;
}

.pay-btn {
  flex: 1;
  padding: 12px;
  border-radius: 20px;
  font-weight: 600;
  font-size: 16px;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .payment-actions {
    max-width: 100%;
    border-radius: 12px 12px 0 0;
    bottom: 50px; /* 在手机端也调整到合适位置 */
  }
}
</style>